package com.r2coding.handler;

import com.r2coding.enums.AuthResultEnum;
import com.r2coding.enums.ResultEnum;
import com.r2coding.exception.CustomException;
import com.r2coding.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author: 98k灬
 * @since: 2022/10/31
 * @email: 98k_style@sina.com
 * @公众号: 爪哇Guy灬
 **/
@Slf4j
@RestControllerAdvice(basePackages = "com.r2coding")
public class GlobalExceptionHandler {
    /**
     * 自定义异常
     *
     * @param exception 异常信息
     * @return 统一响应体
     */
    @ExceptionHandler(value = CustomException.class)
    public Result customException(CustomException exception) {
        log.error("serviceException: {}", exception.getMessage());
        log.error("serviceException: {}", exception.getCode());
        return Result.build(exception.getCode(), exception.getMessage());
    }

    /**
     * 认证失败
     *
     * @param exception 异常信息
     * @return 统一响应体
     */
    @ExceptionHandler(value = BadCredentialsException.class)
    public Result badCredentialsException(BadCredentialsException exception) {
        log.error("badCredentialsException .");
        return Result.build(AuthResultEnum.AUTH_FAIL.getCode(), AuthResultEnum.AUTH_FAIL.getDesc());
    }

    /**
     * 其他异常
     *
     * @param exception 异常信息
     * @return 统一响应体
     */
    @ExceptionHandler(value = Exception.class)
    public Result error(Exception exception) {
        log.error("error: {}", exception.getMessage());
        log.error("error type: {}", exception.getClass());
        return Result.build(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getDesc());
    }
}
